package step1;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class MyServer extends JFrame implements ActionListener {
	JTextArea jta;
	JTextField jtf;
	JButton jb;
	JPanel jp;
	ServerSocket ss;
	Socket socket;
	DataOutputStream out;
	DataInputStream in;

	public MyServer() {
		jta = new JTextArea();
		jtf = new JTextField(15);
		jb = new JButton("发送");
		jp = new JPanel();

		jp.add(jtf);
		jp.add(jb);

		JScrollPane jsp = new JScrollPane(jta);
		this.add(jsp, BorderLayout.CENTER);
		this.add(jp, BorderLayout.SOUTH);

		jb.addActionListener(this);
		jtf.addActionListener(this);

		// 展现
		this.setTitle("服务器");
		this.setSize(300, 200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);

		// 开放端口
		try {
			ss = new ServerSocket(9000);
			System.out.println("等待连接");
			socket = ss.accept();
			System.out.println("已连接");

			out = new DataOutputStream(socket.getOutputStream());
			in = new DataInputStream(socket.getInputStream());
			while (true) {
				// 接受客户端发送数据
				String str = in.readUTF();
				// 显示多行文本框中
				jta.append("客户端说：" + str + "\r\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new MyServer();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jb || e.getSource() == jtf) {
			// 向客户端发送数据
			try {
				out.writeUTF(jtf.getText());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			// 向多行文本框输入历史聊天记录信息
			jta.append("服务器说：" + jtf.getText() + "\r\n");
			// 清空单行文本框内容
			jtf.setText("");

		}
	}
}
